package com.uniflow.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.uniflow.common.PageResult;
import com.uniflow.entity.TaskCenter;
import com.uniflow.entity.Form;
import com.uniflow.entity.FormData;
import com.uniflow.mapper.TaskCenterMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 任务中心服务类
 */
@Service
@Transactional
public class TaskCenterService extends ServiceImpl<TaskCenterMapper, TaskCenter> {
    
    @Autowired
    private TaskCenterMapper taskCenterMapper;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Autowired
    private UniflowFormService formService;
    
    @Autowired
    private FormDataService formDataService;
    
    @Autowired
    private com.uniflow.util.AuditLogHelper auditLogHelper;
    
    @Autowired
    @Lazy
    private WorkflowService workflowService;
    
    /**
     * 分页查询任务列表
     */
    public PageResult<TaskCenter> getTaskList(int pageNum, int pageSize, String title, 
                                             String type, String category, String status, 
                                             Integer priority, String assigneeId, String createdBy, 
                                             String businessType, String processInstanceId, 
                                             String formId, LocalDateTime startDate, 
                                             LocalDateTime endDate, Boolean overdue, String tags) {
        Page<TaskCenter> page = new Page<>(pageNum, pageSize);
        IPage<TaskCenter> result = taskCenterMapper.selectTaskPage(page, title, type, category, 
                status, priority, assigneeId, createdBy, businessType, processInstanceId, 
                formId, startDate, endDate, overdue, tags);
        
        // 解析JSON字段并设置扩展信息
        result.getRecords().forEach(this::enrichTaskInfo);
        
        return new PageResult<TaskCenter>(pageNum, pageSize, result.getTotal(), result.getRecords());
    }
    
    /**
     * 根据ID查询任务详情
     */
    public TaskCenter getTaskById(String id) {
        TaskCenter task = this.getById(id);
        if (task != null) {
            enrichTaskInfo(task);
        }
        return task;
    }
    
    /**
     * 根据执行人查询任务列表
     */
    public List<TaskCenter> getTasksByAssigneeId(String assigneeId, String status) {
        List<TaskCenter> tasks = taskCenterMapper.selectByAssigneeId(assigneeId, status);
        tasks.forEach(this::enrichTaskInfo);
        return tasks;
    }
    
    /**
     * 根据创建人查询任务列表
     */
    public List<TaskCenter> getTasksByCreatedBy(String createdBy, String status) {
        List<TaskCenter> tasks = taskCenterMapper.selectByCreatedBy(createdBy, status);
        tasks.forEach(this::enrichTaskInfo);
        return tasks;
    }
    
    /**
     * 根据业务键查询任务
     */
    public TaskCenter getTaskByBusinessKey(String businessKey) {
        TaskCenter task = taskCenterMapper.selectByBusinessKey(businessKey);
        if (task != null) {
            enrichTaskInfo(task);
        }
        return task;
    }
    
    /**
     * 根据流程实例ID查询任务列表
     */
    public List<TaskCenter> getTasksByProcessInstanceId(String processInstanceId) {
        List<TaskCenter> tasks = taskCenterMapper.selectByProcessInstanceId(processInstanceId);
        tasks.forEach(this::enrichTaskInfo);
        return tasks;
    }
    
    /**
     * 根据流程任务ID查询任务
     */
    public TaskCenter getTaskByProcessTaskId(String processTaskId) {
        TaskCenter task = taskCenterMapper.selectByProcessTaskId(processTaskId);
        if (task != null) {
            enrichTaskInfo(task);
        }
        return task;
    }
    
    /**
     * 根据表单ID查询任务列表
     */
    public List<TaskCenter> getTasksByFormId(String formId) {
        List<TaskCenter> tasks = taskCenterMapper.selectByFormId(formId);
        tasks.forEach(this::enrichTaskInfo);
        return tasks;
    }
    
    /**
     * 根据表单数据ID查询任务
     */
    public TaskCenter getTaskByFormDataId(String formDataId) {
        TaskCenter task = taskCenterMapper.selectByFormDataId(formDataId);
        if (task != null) {
            enrichTaskInfo(task);
        }
        return task;
    }
    
    /**
     * 查询我的任务列表
     */
    public PageResult<TaskCenter> getMyTasks(int pageNum, int pageSize, String userId, 
                                           String status, String type, Integer priority, 
                                           Boolean overdue) {
        Page<TaskCenter> page = new Page<>(pageNum, pageSize);
        IPage<TaskCenter> result = taskCenterMapper.selectMyTasks(page, userId, status, 
                type, priority, overdue);
        
        result.getRecords().forEach(this::enrichTaskInfo);
        
        return new PageResult<TaskCenter>(pageNum, pageSize, result.getTotal(), result.getRecords());
    }
    
    /**
     * 查询我创建的任务列表
     */
    public PageResult<TaskCenter> getMyCreatedTasks(int pageNum, int pageSize, String userId, 
                                                   String status, String type) {
        Page<TaskCenter> page = new Page<>(pageNum, pageSize);
        IPage<TaskCenter> result = taskCenterMapper.selectMyCreatedTasks(page, userId, status, type);
        
        result.getRecords().forEach(this::enrichTaskInfo);
        
        return new PageResult<TaskCenter>(pageNum, pageSize, result.getTotal(), result.getRecords());
    }
    
    /**
     * 查询候选任务列表（可认领的任务）
     */
    public PageResult<TaskCenter> getCandidateTasks(int pageNum, int pageSize, String userId, 
                                                   List<String> userGroups, String type, 
                                                   Integer priority) {
        Page<TaskCenter> page = new Page<>(pageNum, pageSize);
        IPage<TaskCenter> result = taskCenterMapper.selectCandidateTasks(page, userId, 
                userGroups, type, priority);
        
        result.getRecords().forEach(this::enrichTaskInfo);
        
        return new PageResult<TaskCenter>(pageNum, pageSize, result.getTotal(), result.getRecords());
    }
    
    /**
     * 查询过期任务列表
     */
    public PageResult<TaskCenter> getOverdueTasks(int pageNum, int pageSize, String assigneeId, 
                                                 String type) {
        Page<TaskCenter> page = new Page<>(pageNum, pageSize);
        IPage<TaskCenter> result = taskCenterMapper.selectOverdueTasks(page, assigneeId, type);
        
        result.getRecords().forEach(this::enrichTaskInfo);
        
        return new PageResult<TaskCenter>(pageNum, pageSize, result.getTotal(), result.getRecords());
    }
    
    /**
     * 查询即将到期的任务列表
     */
    public PageResult<TaskCenter> getUpcomingTasks(int pageNum, int pageSize, String assigneeId, 
                                                  Integer hours) {
        Page<TaskCenter> page = new Page<>(pageNum, pageSize);
        IPage<TaskCenter> result = taskCenterMapper.selectUpcomingTasks(page, assigneeId, hours);
        
        result.getRecords().forEach(this::enrichTaskInfo);
        
        return new PageResult<TaskCenter>(pageNum, pageSize, result.getTotal(), result.getRecords());
    }
    
    /**
     * 创建任务
     */
    public TaskCenter createTask(TaskCenter task) {
        // 验证必填字段
        if (!StringUtils.hasText(task.getTitle())) {
            throw new RuntimeException("任务标题不能为空");
        }
        
        // 设置默认值
        if (!StringUtils.hasText(task.getId())) {
            task.setId(UUID.randomUUID().toString());
        }
        if (task.getPriority() == null) {
            task.setPriority(2); // 默认普通优先级
        }
        if (!StringUtils.hasText(task.getStatus())) {
            task.setStatus("created");
        }
        if (task.getStartTime() == null) {
            task.setStartTime(LocalDateTime.now());
        }
        if (task.getSort() == null) {
            Integer maxSort = taskCenterMapper.getMaxSort();
            task.setSort(maxSort != null ? maxSort + 1 : 1);
        }
        if (task.getDeleted() == null) {
            task.setDeleted(false);
        }
        
        // 序列化JSON字段
        serializeJsonFields(task);
        
        this.save(task);
        
        // 记录审计日志
        auditLogHelper.recordCreate("TASK_CENTER", task.getId(), task.getTitle(), 
                                   task.getCreatedBy(), null);
        
        return task;
    }
    
    /**
     * 更新任务
     */
    public TaskCenter updateTask(TaskCenter task) {
        TaskCenter existingTask = this.getById(task.getId());
        if (existingTask == null) {
            throw new RuntimeException("任务不存在");
        }
        
        // 验证任务状态
        if ("completed".equals(existingTask.getStatus()) || "cancelled".equals(existingTask.getStatus())) {
            throw new RuntimeException("已完成或已取消的任务不能修改");
        }
        
        // 序列化JSON字段
        serializeJsonFields(task);
        
        this.updateById(task);
        
        // 记录审计日志
        auditLogHelper.recordUpdate("TASK_CENTER", task.getId(), task.getTitle(), 
                                   task.getUpdatedBy(), null, null);
        
        return task;
    }
    
    /**
     * 删除任务
     */
    public void deleteTask(String id) {
        TaskCenter task = this.getById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        // 验证任务状态
        if ("in_progress".equals(task.getStatus())) {
            throw new RuntimeException("进行中的任务不能删除");
        }
        
        this.removeById(id);
    }
    
    /**
     * 批量删除任务
     */
    public void batchDeleteTasks(List<String> ids) {
        for (String id : ids) {
            deleteTask(id);
        }
    }
    
    /**
     * 分配任务
     */
    public void assignTask(String id, String assigneeId, String assigneeName, 
                          String updatedBy, String updatedByName) {
        TaskCenter task = this.getById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        if ("completed".equals(task.getStatus()) || "cancelled".equals(task.getStatus())) {
            throw new RuntimeException("已完成或已取消的任务不能分配");
        }
        
        int result = taskCenterMapper.assignTask(id, assigneeId, assigneeName, updatedBy, updatedByName);
        if (result > 0) {
            // 更新任务状态为已分配
            taskCenterMapper.updateTaskStatus(id, "assigned", updatedBy, updatedByName);
        }
    }
    
    /**
     * 批量分配任务
     */
    public void batchAssignTask(List<String> ids, String assigneeId, String assigneeName, 
                               String updatedBy, String updatedByName) {
        for (String id : ids) {
            assignTask(id, assigneeId, assigneeName, updatedBy, updatedByName);
        }
    }
    
    /**
     * 认领任务
     */
    public void claimTask(String id, String userId, String userName) {
        TaskCenter task = this.getById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        if (StringUtils.hasText(task.getAssigneeId())) {
            throw new RuntimeException("任务已被分配，不能认领");
        }
        
        if ("completed".equals(task.getStatus()) || "cancelled".equals(task.getStatus())) {
            throw new RuntimeException("已完成或已取消的任务不能认领");
        }
        
        assignTask(id, userId, userName, userId, userName);
    }
    
    /**
     * 开始任务
     */
    public void startTask(String id, String userId, String userName) {
        TaskCenter task = this.getById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        if (!userId.equals(task.getAssigneeId())) {
            throw new RuntimeException("只有任务执行人才能开始任务");
        }
        
        if ("in_progress".equals(task.getStatus())) {
            throw new RuntimeException("任务已在进行中");
        }
        
        if ("completed".equals(task.getStatus()) || "cancelled".equals(task.getStatus())) {
            throw new RuntimeException("已完成或已取消的任务不能开始");
        }
        
        taskCenterMapper.updateTaskStatus(id, "in_progress", userId, userName);
    }
    
    /**
     * 暂停任务
     */
    public void suspendTask(String id, String userId, String userName) {
        TaskCenter task = this.getById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        if (!userId.equals(task.getAssigneeId())) {
            throw new RuntimeException("只有任务执行人才能暂停任务");
        }
        
        if (!"in_progress".equals(task.getStatus())) {
            throw new RuntimeException("只有进行中的任务才能暂停");
        }
        
        taskCenterMapper.updateTaskStatus(id, "suspended", userId, userName);
    }
    
    /**
     * 恢复任务
     */
    public void resumeTask(String id, String userId, String userName) {
        TaskCenter task = this.getById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        if (!userId.equals(task.getAssigneeId())) {
            throw new RuntimeException("只有任务执行人才能恢复任务");
        }
        
        if (!"suspended".equals(task.getStatus())) {
            throw new RuntimeException("只有暂停的任务才能恢复");
        }
        
        taskCenterMapper.updateTaskStatus(id, "in_progress", userId, userName);
    }
    
    /**
     * 完成任务
     */
    public void completeTask(String id, String userId, String userName) {
        TaskCenter task = this.getById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        if (!userId.equals(task.getAssigneeId())) {
            throw new RuntimeException("只有任务执行人才能完成任务");
        }
        
        if ("completed".equals(task.getStatus())) {
            throw new RuntimeException("任务已完成");
        }
        
        if ("cancelled".equals(task.getStatus())) {
            throw new RuntimeException("已取消的任务不能完成");
        }
        
        LocalDateTime completedTime = LocalDateTime.now();
        taskCenterMapper.completeTask(id, completedTime, userId, userName);
        taskCenterMapper.updateTaskStatus(id, "completed", userId, userName);
        
        // 记录审计日志
        auditLogHelper.recordLog("COMPLETE", "TASK_CENTER", id, task.getTitle(), 
                                "完成任务: " + task.getTitle(), "SUCCESS", userId, null, null);
        
        // 如果是流程任务，同步完成流程任务
        if (StringUtils.hasText(task.getProcessTaskId())) {
            try {
                Map<String, Object> variables = new HashMap<>();
                variables.put("taskResult", "completed");
                variables.put("completedBy", userName);
                workflowService.completeTask(task.getProcessTaskId(), variables, "任务完成");
            } catch (Exception e) {
                System.err.println("同步完成流程任务失败: " + e.getMessage());
            }
        }
    }
    
    /**
     * 取消任务
     */
    public void cancelTask(String id, String userId, String userName) {
        TaskCenter task = this.getById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        if ("completed".equals(task.getStatus())) {
            throw new RuntimeException("已完成的任务不能取消");
        }
        
        if ("cancelled".equals(task.getStatus())) {
            throw new RuntimeException("任务已取消");
        }
        
        taskCenterMapper.updateTaskStatus(id, "cancelled", userId, userName);
    }
    
    /**
     * 审批任务（同意）
     */
    public void approveTask(String id, String comment, Map<String, Object> variables, String userId, String userName) {
        TaskCenter task = this.getById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        if (!userId.equals(task.getAssigneeId())) {
            throw new RuntimeException("只有任务执行人才能审批任务");
        }
        
        if ("completed".equals(task.getStatus()) || "cancelled".equals(task.getStatus())) {
            throw new RuntimeException("已完成或已取消的任务不能审批");
        }
        
        // 添加审批意见到扩展信息
        Map<String, Object> extend = task.getExtend();
        if (extend == null) {
            extend = new HashMap<>();
        }
        extend.put("approvalComment", comment);
        extend.put("approvalResult", "approved");
        extend.put("approvalTime", LocalDateTime.now());
        extend.put("approvalUserId", userId);
        extend.put("approvalUserName", userName);
        
        if (variables != null) {
            extend.putAll(variables);
        }
        
        task.setExtend(extend);
        serializeJsonFields(task);
        
        // 更新任务状态为已完成
        taskCenterMapper.updateTaskStatus(id, "completed", userId, userName);
        taskCenterMapper.updateById(task);
    }
    
    /**
     * 拒绝任务（驳回）
     */
    public void rejectTask(String id, String reason, Map<String, Object> variables, String userId, String userName) {
        TaskCenter task = this.getById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        if (!userId.equals(task.getAssigneeId())) {
            throw new RuntimeException("只有任务执行人才能拒绝任务");
        }
        
        if ("completed".equals(task.getStatus()) || "cancelled".equals(task.getStatus())) {
            throw new RuntimeException("已完成或已取消的任务不能拒绝");
        }
        
        // 添加拒绝理由到扩展信息
        Map<String, Object> extend = task.getExtend();
        if (extend == null) {
            extend = new HashMap<>();
        }
        extend.put("rejectReason", reason);
        extend.put("approvalResult", "rejected");
        extend.put("rejectTime", LocalDateTime.now());
        extend.put("rejectUserId", userId);
        extend.put("rejectUserName", userName);
        
        if (variables != null) {
            extend.putAll(variables);
        }
        
        task.setExtend(extend);
        serializeJsonFields(task);
        
        // 更新任务状态为已拒绝
        taskCenterMapper.updateTaskStatus(id, "rejected", userId, userName);
        taskCenterMapper.updateById(task);
    }
    
    /**
     * 转办任务
     */
    public void transferTask(String id, String targetUserId, String targetUserName, String reason, String userId, String userName) {
        TaskCenter task = this.getById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        if (!userId.equals(task.getAssigneeId())) {
            throw new RuntimeException("只有任务执行人才能转办任务");
        }
        
        if ("completed".equals(task.getStatus()) || "cancelled".equals(task.getStatus())) {
            throw new RuntimeException("已完成或已取消的任务不能转办");
        }
        
        if (StringUtils.isEmpty(targetUserId)) {
            throw new RuntimeException("转办目标用户不能为空");
        }
        
        // 添加转办记录到扩展信息
        Map<String, Object> extend = task.getExtend();
        if (extend == null) {
            extend = new HashMap<>();
        }
        extend.put("transferReason", reason);
        extend.put("transferTime", LocalDateTime.now());
        extend.put("transferFromUserId", userId);
        extend.put("transferFromUserName", userName);
        extend.put("transferToUserId", targetUserId);
        extend.put("transferToUserName", targetUserName);
        
        task.setExtend(extend);
        serializeJsonFields(task);
        
        // 分配给新的执行人
        assignTask(id, targetUserId, targetUserName, userId, userName);
        taskCenterMapper.updateById(task);
    }
    
    /**
     * 更新任务状态
     */
    public void updateTaskStatus(String id, String status, String updatedBy, String updatedByName) {
        TaskCenter task = this.getById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        taskCenterMapper.updateTaskStatus(id, status, updatedBy, updatedByName);
    }
    
    /**
     * 批量更新任务状态
     */
    public void batchUpdateTaskStatus(List<String> ids, String status, String updatedBy, 
                                     String updatedByName) {
        taskCenterMapper.batchUpdateTaskStatus(ids, status, updatedBy, updatedByName);
    }
    
    /**
     * 更新任务优先级
     */
    public void updateTaskPriority(String id, Integer priority, String updatedBy, 
                                  String updatedByName) {
        TaskCenter task = this.getById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        if (priority < 1 || priority > 5) {
            throw new RuntimeException("优先级必须在1-5之间");
        }
        
        taskCenterMapper.updateTaskPriority(id, priority, updatedBy, updatedByName);
    }
    
    /**
     * 批量更新任务优先级
     */
    public void batchUpdateTaskPriority(List<String> ids, Integer priority, String updatedBy, 
                                       String updatedByName) {
        if (priority < 1 || priority > 5) {
            throw new RuntimeException("优先级必须在1-5之间");
        }
        
        taskCenterMapper.batchUpdateTaskPriority(ids, priority, updatedBy, updatedByName);
    }
    
    /**
     * 更新任务到期时间
     */
    public void updateTaskDueTime(String id, LocalDateTime dueTime, String updatedBy, 
                                 String updatedByName) {
        TaskCenter task = this.getById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        taskCenterMapper.updateTaskDueTime(id, dueTime, updatedBy, updatedByName);
    }
    
    /**
     * 批量更新任务到期时间
     */
    public void batchUpdateTaskDueTime(List<String> ids, LocalDateTime dueTime, String updatedBy, 
                                      String updatedByName) {
        taskCenterMapper.batchUpdateTaskDueTime(ids, dueTime, updatedBy, updatedByName);
    }
    
    /**
     * 更新任务标签
     */
    public void updateTaskTags(String id, List<String> tags, String updatedBy, String updatedByName) {
        TaskCenter task = this.getById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        String tagsStr = tags != null ? String.join(",", tags) : null;
        taskCenterMapper.updateTaskTags(id, tagsStr, updatedBy, updatedByName);
    }
    
    /**
     * 批量更新任务标签
     */
    public void batchUpdateTaskTags(List<String> ids, List<String> tags, String updatedBy, 
                                   String updatedByName) {
        String tagsStr = tags != null ? String.join(",", tags) : null;
        taskCenterMapper.batchUpdateTaskTags(ids, tagsStr, updatedBy, updatedByName);
    }
    
    /**
     * 批量更新任务排序
     */
    public void batchUpdateTaskSort(List<Map<String, Object>> taskSorts) {
        taskCenterMapper.batchUpdateTaskSort(taskSorts);
    }
    
    /**
     * 检查业务键是否存在
     */
    public boolean isBusinessKeyExists(String businessKey, String excludeId) {
        return taskCenterMapper.checkBusinessKeyExists(businessKey, excludeId) > 0;
    }
    
    /**
     * 获取任务统计信息
     */
    public Map<String, Object> getTaskStatistics(String assigneeId) {
        return taskCenterMapper.getTaskStatistics(assigneeId);
    }
    
    /**
     * 根据状态统计任务数量
     */
    public List<Map<String, Object>> getTaskCountByStatus(String assigneeId) {
        return taskCenterMapper.getTaskCountByStatus(assigneeId);
    }
    
    /**
     * 根据类型统计任务数量
     */
    public List<Map<String, Object>> getTaskCountByType(String assigneeId, Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        return taskCenterMapper.getTaskCountByType(assigneeId, limit);
    }
    
    /**
     * 根据分类统计任务数量
     */
    public List<Map<String, Object>> getTaskCountByCategory(String assigneeId, Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        return taskCenterMapper.getTaskCountByCategory(assigneeId, limit);
    }
    
    /**
     * 根据优先级统计任务数量
     */
    public List<Map<String, Object>> getTaskCountByPriority(String assigneeId) {
        return taskCenterMapper.getTaskCountByPriority(assigneeId);
    }
    
    /**
     * 根据创建人统计任务数量
     */
    public List<Map<String, Object>> getTaskCountByCreator(Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        return taskCenterMapper.getTaskCountByCreator(limit);
    }
    
    /**
     * 根据执行人统计任务数量
     */
    public List<Map<String, Object>> getTaskCountByAssignee(Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        return taskCenterMapper.getTaskCountByAssignee(limit);
    }
    
    /**
     * 根据时间统计任务数量
     */
    public List<Map<String, Object>> getTaskCountByDate(String assigneeId, LocalDateTime startDate, 
                                                       LocalDateTime endDate) {
        return taskCenterMapper.getTaskCountByDate(assigneeId, startDate, endDate);
    }
    
    /**
     * 根据时间统计任务数量（按月）
     */
    public List<Map<String, Object>> getTaskCountByMonth(String assigneeId, LocalDateTime startDate, 
                                                        LocalDateTime endDate) {
        return taskCenterMapper.getTaskCountByMonth(assigneeId, startDate, endDate);
    }
    
    /**
     * 获取任务完成率统计
     */
    public Map<String, Object> getTaskCompletionRate(String assigneeId, LocalDateTime startDate, 
                                                     LocalDateTime endDate) {
        return taskCenterMapper.getTaskCompletionRate(assigneeId, startDate, endDate);
    }
    
    /**
     * 获取任务平均处理时间
     */
    public Map<String, Object> getTaskAverageProcessingTime(String assigneeId, String type, 
                                                           LocalDateTime startDate, 
                                                           LocalDateTime endDate) {
        return taskCenterMapper.getTaskAverageProcessingTime(assigneeId, type, startDate, endDate);
    }
    
    /**
     * 获取过期任务统计
     */
    public Map<String, Object> getOverdueTaskStatistics(String assigneeId) {
        return taskCenterMapper.getOverdueTaskStatistics(assigneeId);
    }
    
    /**
     * 获取待处理任务数量
     */
    public int getPendingTaskCount(String assigneeId) {
        return taskCenterMapper.getPendingTaskCount(assigneeId);
    }
    
    /**
     * 获取今日新增任务数量
     */
    public int getTodayNewTaskCount(String assigneeId) {
        return taskCenterMapper.getTodayNewTaskCount(assigneeId);
    }
    
    /**
     * 获取今日完成任务数量
     */
    public int getTodayCompletedTaskCount(String assigneeId) {
        return taskCenterMapper.getTodayCompletedTaskCount(assigneeId);
    }
    
    /**
     * 获取本周任务统计
     */
    public Map<String, Object> getWeeklyTaskStatistics(String assigneeId) {
        return taskCenterMapper.getWeeklyTaskStatistics(assigneeId);
    }
    
    /**
     * 获取本月任务统计
     */
    public Map<String, Object> getMonthlyTaskStatistics(String assigneeId) {
        return taskCenterMapper.getMonthlyTaskStatistics(assigneeId);
    }
    
    /**
     * 查询任务分类列表
     */
    public List<String> getTaskCategories() {
        return taskCenterMapper.getTaskCategories();
    }
    
    /**
     * 查询任务类型列表
     */
    public List<String> getTaskTypes() {
        return taskCenterMapper.getTaskTypes();
    }
    
    /**
     * 查询任务标签列表
     */
    public List<String> getTaskTags(Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 20;
        }
        return taskCenterMapper.getTaskTags(limit);
    }
    
    /**
     * 查询相关任务列表
     */
    public List<TaskCenter> getRelatedTasks(String businessKey, String businessType, String excludeId) {
        List<TaskCenter> tasks = taskCenterMapper.selectRelatedTasks(businessKey, businessType, excludeId);
        tasks.forEach(this::enrichTaskInfo);
        return tasks;
    }
    
    /**
     * 查询任务依赖关系
     */
    public List<Map<String, Object>> getTaskDependencies(String taskId) {
        return taskCenterMapper.getTaskDependencies(taskId);
    }
    
    /**
     * 查询子任务列表
     */
    public List<TaskCenter> getSubTasks(String parentTaskId) {
        List<TaskCenter> tasks = taskCenterMapper.selectSubTasks(parentTaskId);
        tasks.forEach(this::enrichTaskInfo);
        return tasks;
    }
    
    /**
     * 查询父任务
     */
    public TaskCenter getParentTask(String taskId) {
        TaskCenter task = taskCenterMapper.selectParentTask(taskId);
        if (task != null) {
            enrichTaskInfo(task);
        }
        return task;
    }
    
    /**
     * 根据流程实例ID删除任务
     */
    public void deleteTasksByProcessInstanceId(String processInstanceId) {
        taskCenterMapper.deleteByProcessInstanceId(processInstanceId);
    }
    
    /**
     * 根据表单ID删除任务
     */
    public void deleteTasksByFormId(String formId) {
        taskCenterMapper.deleteByFormId(formId);
    }
    
    /**
     * 根据表单数据ID删除任务
     */
    public void deleteTasksByFormDataId(String formDataId) {
        taskCenterMapper.deleteByFormDataId(formDataId);
    }
    
    /**
     * 丰富任务信息
     */
    private void enrichTaskInfo(TaskCenter task) {
        // 解析JSON字段
        parseJsonFields(task);
        
        // 设置扩展信息
        task.setDuration(task.getDuration());
        task.setOverdue(task.isOverdue());
        task.setRemainingTime(task.getRemainingTime());
        
        // 解析标签
        if (StringUtils.hasText(task.getTags())) {
            task.setTagList(Arrays.asList(task.getTags().split(",")));
        }
        
        // 加载表单信息
        enrichFormInfo(task);
    }
    
    /**
     * 丰富表单信息
     */
    private void enrichFormInfo(TaskCenter task) {
        TaskCenter.FormInfo formInfo = new TaskCenter.FormInfo();
        boolean hasFormInfo = false;
        
        // 如果任务有关联的表单ID，加载表单定义信息
        if (StringUtils.hasText(task.getFormId())) {
            try {
                Form form = formService.getFormById(task.getFormId());
                if (form != null) {
                    formInfo.setFormId(form.getId());
                    formInfo.setFormName(form.getName());
                    formInfo.setFormTitle(form.getTitle());
                    formInfo.setFormUrl("/forms/" + form.getId());
                    hasFormInfo = true;
                }
            } catch (Exception e) {
                // 忽略加载错误
            }
        }
        
        // 如果任务有关联的表单数据ID，加载表单数据信息
        if (StringUtils.hasText(task.getFormDataId())) {
            try {
                FormData formData = formDataService.getFormDataById(task.getFormDataId());
                if (formData != null) {
                    formInfo.setFormDataId(formData.getId());
                    // 如果表单定义信息还没有加载，从表单数据中获取
                    if (!hasFormInfo && StringUtils.hasText(formData.getFormId())) {
                        Form form = formService.getFormById(formData.getFormId());
                        if (form != null) {
                            formInfo.setFormId(form.getId());
                            formInfo.setFormName(form.getName());
                            formInfo.setFormTitle(form.getTitle());
                            formInfo.setFormUrl("/forms/" + form.getId());
                        }
                    }
                    hasFormInfo = true;
                }
            } catch (Exception e) {
                // 忽略加载错误
            }
        }
        
        // 如果没有直接的表单关联，尝试通过任务ID查找表单数据
        if (!hasFormInfo && StringUtils.hasText(task.getId())) {
            try {
                FormData formData = formDataService.getFormDataByTaskId(task.getId());
                if (formData != null) {
                    formInfo.setFormDataId(formData.getId());
                    if (StringUtils.hasText(formData.getFormId())) {
                        Form form = formService.getFormById(formData.getFormId());
                        if (form != null) {
                            formInfo.setFormId(form.getId());
                            formInfo.setFormName(form.getName());
                            formInfo.setFormTitle(form.getTitle());
                            formInfo.setFormUrl("/forms/" + form.getId());
                        }
                    }
                    hasFormInfo = true;
                }
            } catch (Exception e) {
                // 忽略加载错误
            }
        }
        
        // 设置表单信息到任务对象
        if (hasFormInfo) {
            task.setFormInfo(formInfo);
        }
    }
    
    /**
     * 解析JSON字段
     */
    private void parseJsonFields(TaskCenter task) {
        try {
            if (StringUtils.hasText(task.getBusinessDataJson())) {
                Map<String, Object> businessData = objectMapper.readValue(
                        task.getBusinessDataJson(), new TypeReference<Map<String, Object>>() {});
                task.setBusinessData(businessData);
            }
            
            if (StringUtils.hasText(task.getExtendJson())) {
                Map<String, Object> extend = objectMapper.readValue(
                        task.getExtendJson(), new TypeReference<Map<String, Object>>() {});
                task.setExtend(extend);
            }
        } catch (Exception e) {
            // 忽略JSON解析错误
        }
    }
    
    /**
     * 序列化JSON字段
     */
    private void serializeJsonFields(TaskCenter task) {
        try {
            if (task.getBusinessData() != null) {
                task.setBusinessDataJson(objectMapper.writeValueAsString(task.getBusinessData()));
            }
            
            if (task.getExtend() != null) {
                task.setExtendJson(objectMapper.writeValueAsString(task.getExtend()));
            }
            
            if (task.getTagList() != null && !task.getTagList().isEmpty()) {
                task.setTags(String.join(",", task.getTagList()));
            }
        } catch (Exception e) {
            throw new RuntimeException("序列化任务JSON字段失败", e);
        }
    }
}